import AttachmentInput from "../components/AttachmentInput/AttachmentInput";
import BubbleChat from "../components/BubbleChat/BubbleChat";
import useStyle from '../views/Index/index';
import React, { useEffect, useState } from "react";
import { useXAgent, useXChat, XRequest, XStream } from "@ant-design/x";
import { message, Space, Dropdown, Button } from "antd";
import WelcomeMessage from "../components/WelcomeMessage/WelcomeMessage";
import TipsPrompts from "../components/TipsPrompts/TipsPrompts";
import ConversationsManger from "../components/ConversationsManger/ConversationsManger.js";
import logo from "../assets/images/医路同行logo.png";
import axios from "axios";
import markdownit from 'markdown-it';
import { v4 as uuidv4 } from 'uuid';
import ContentRenderer from "../utils/ContentRenderer";
import { DownOutlined } from '@ant-design/icons';
import ModelDropdown from "../components/ModelDropdown/ModelDropdown.js";
import { getToken } from "../utils/auth.js";

const RenderMarkdown = (content) => {
  const md = new markdownit();
  return <div dangerouslySetInnerHTML={{ __html: md.render(content) }} />;
};

const BASE_URL = process.env.REACT_APP_API_BASE_URL || "http://localhost:8000";
const PATH = process.env.REACT_APP_API_PATH || "/qwen/chat";

const ChatRight = () => {
  const { styles } = useStyle();

  const [content, setContent] = useState('');
  const [conversationsItems, setConversationsItems] = useState([]);
  const [activeKey, setActiveKey] = useState("init");
  const [loading, setLoading] = useState(false);
  const [historyMessages, setHistoryMessages] = useState([]);
  const [conversationId, setConversationId] = useState(null);
  const [selectedModel, setSelectedModel] = useState("qwen2.5-72b-instruct");

  const [agent] = useXAgent({
    baseURL: `${BASE_URL}${PATH}`,
  });

  const { onRequest, messages, setMessages } = useXChat({
    agent,
    requestPlaceholder: 'Waiting...',  //请求中的占位信息，不提供则不会展示
    requestFallback: 'Request failed. Please try again later.', //请求失败的兜底信息，不提供则不会展示
  });

  //对话列表 配置
  const messagesItems = messages.map(({ id, message, role }, index) => ({
    key: id,
    loading: false,
    role: role === 'user' ? 'user' : 'ai',
    content: message,
    // messageRender: { RenderMarkdown },
  }));

  useEffect(() => {
    const fetchConversations = async () => {
      try {
        const response = await axios.get(`${BASE_URL}${PATH}/conversations`, {
          headers: {
            Authorization: `Bearer ${getToken()}`
          }
        });
        const conversations = response.data.data || [];
        if (conversations.length > 0) {
          const formattedConversations = conversations.map(conversation => ({
            key: conversation.conversation_id,
            label: conversation.title,
          }));
          setConversationsItems(formattedConversations);
          if (activeKey === "AddConversation"){
            setActiveKey(formattedConversations[0].key);
            setConversationId(formattedConversations[0].key);
          }
        } else {
          setConversationsItems([]);
          setActiveKey(null);
          setConversationId(null);
        }
      } catch (error) {
        console.error('Error fetching conversations:', error);
        // message.error('请重新登录');
      }
    };

    const fetchConversationDetails = async () => {
      if (!conversationId) return;

      try {
        const response = await axios.get(`${BASE_URL}${PATH}/conversations/${conversationId}`, {
          headers: {
            Authorization: `Bearer ${getToken()}`
          }
        });
        const conversationDetails = response.data.data || [];
        const formattedMessages = conversationDetails.map(msg => ({
          id: msg.message_id,
          message: <ContentRenderer content={msg.content} />,
          role: msg.sender_type,
        }));
        // setHistoryMessages(conversationDetails);
        setMessages(formattedMessages);
      } catch (error) {
        console.error('Error fetching conversation details:', error);
        // message.error('请登录后再试');
        setHistoryMessages([]);
      }
    };

    if (activeKey === "init"){
      fetchConversations();
    }
    else if (activeKey === "AddConversation") {
      fetchConversations();
    }
    else if (activeKey === null) {
      // setConversationsItems([]);
      
    }
    else {
      fetchConversationDetails();
      // console.log(messages);
    }

  }, [activeKey]);



  // const fetchRequest = XRequest({
  //   baseURL: `${BASE_URL}${PATH}/chat`,
  //   fetch: (url, options) => fetch(url, {
  //     method: 'POST',
  //     body: options.body,
  //     headers: {
  //       Authorization: `Bearer ${getToken()}`
  //     }
  //   })
  //     .then(response => response)
  //     .catch(error => {
  //       console.error('Fetch error:', error);
  //       throw error;
  //     }),
  // });

  const fetchRequest = XRequest({
    baseURL: `${BASE_URL}${PATH}/chat`,
    fetch: (url, options) => {
      const controller = new AbortController();
      const signal = controller.signal;
  
      const timeoutId = setTimeout(() => {
        controller.abort();
      }, 300000); // 设置超时时间为10秒
      try{
        return fetch(url, {
          method: 'POST',
          body: options.body,
          headers: {
            Authorization: `Bearer ${getToken()}`,
          },
          signal: signal,
        })
          .then(response => {
            // clearTimeout(timeoutId);
            return response;
          })
    }  catch (error) {
        console.error('Fetch error:', error);
        // throw error;
      }
        
    },
  });

  async function requestChat(question) {
    const userMessage = {
      id: uuidv4(),
      message: question,
      role: "user",
    };

    const assistantMessage = {
      id: uuidv4(),
      message: <ContentRenderer content="等待中..." />,
      role: "ai",
    };

    setMessages((prevMessages) => [...prevMessages, userMessage, assistantMessage]);
    

    setLoading(true);
    let newContent = '';
    try {
       fetchRequest.create(
        {
          message: question,
          history: historyMessages,
          stream: true,
          model: selectedModel,
          conversation_id: conversationId,
        },
        {
          onUpdate: (response) => {
            if (conversationId === null) {
                setActiveKey("AddConversation");
            }
            newContent = newContent +JSON.parse(response.data).data[0].choices[0].delta.content;
            setMessages((prevMessages) =>
              prevMessages.map((msg) =>
                msg.id === assistantMessage.id
                  ? { ...msg, message: <ContentRenderer content={newContent} /> }
                  : msg
              )
            );

          },
          onSuccess: () => {
            setLoading(false);
            // 更新历史消息,保持多轮对话
            setHistoryMessages((prevHistory) => [
              ...prevHistory,
              {
                role: "user",
                content: question,
              },
              {
                role: "assistant",
                content: newContent,
              },
            ]);
          },
          onError: (e) => {
            
            console.error("请求有错误！", e);
            message.error('登录过期，或稍后再试');
            setLoading(false);
          },
        }
      );

    } catch (error) {
      console.error("请求有错误！", error);
      setLoading(false);
    }
  }



  const onSubmit = (nextContent) => {
    if (!nextContent) return;
    requestChat(nextContent);
    setContent('');  //清空输入框
    setLoading(true); // 显示发送按钮 loading 状态
    
  };

  const handlePromptsItemClick = (info) => {
    onSubmit(info.data.description);
    setHistoryMessages([]); // 清空历史消息
    setContent(''); //清空输入框
  };

 

  const onAddConversation = async () => {
    if (messages.length !== 0){
      setMessages([]); // 清空当前消息
      setHistoryMessages([]); // 清空当前历史消息
      setConversationId(null); // 清空当前会话ID
      setActiveKey(null); // 清空当前激活会话ID
    }else{
      message.info("已是最新会话");
    }
    
  };

  const onConversationClick = (key) => {
    setActiveKey(key);
    setConversationId(key);
    setHistoryMessages([]); // 清空历史消息
    console.log('Conversation Id:', key);
  };

  const handleModelSelect = (selectedItem) => {
    setSelectedModel(selectedItem.label);
    console.log('Selected Model:', selectedModel);
  };

  const placeholderNode = (
    <div > {/* 确保父容器有高度 */}
      <Space direction="vertical" size={16} className={styles.placeholder}>
        <WelcomeMessage />
        <TipsPrompts onPromptsItemClick={handlePromptsItemClick} />
      </Space>
    </div>
  );

  return (
    <div className={styles.layout}>
      <div className={styles.menu}>
        <ConversationsManger
          onAddConversation={onAddConversation}
          onConversationClick={onConversationClick}
          conversationsItems={conversationsItems}
          activeKey={activeKey}
        />
      </div>
      {/* <ModelDropdown onSelect={handleModelSelect} /> */}
      <div className={styles.chat}>
        <BubbleChat
          items={messagesItems}
          placeholderNode={placeholderNode}
          RenderMarkdown={RenderMarkdown}
        />
        <AttachmentInput
          styles={styles}
          onSubmit={onSubmit}
          content={content}
          setContent={setContent}
          loading={loading}
          setLoading={setLoading}
        />
      </div>
    </div>
  );
};

export default ChatRight;